package com.sws.push.service.impl;

import com.alibaba.fastjson2.JSON;
import com.sws.customer.domain.RyCustomer;
import com.sws.customer.mapper.RyCustomerMapper;
import com.sws.push.domain.*;
import com.sws.push.mapper.AiModelConfigMapper;
import com.sws.push.mapper.RyConsumptionMapper;
import com.sws.push.mapper.RyProductMapper;
import com.sws.push.mapper.RyServiceMapper;
import com.sws.push.service.AIDialogue;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class AIDialogueImpl implements AIDialogue {


    private final ChatClient aIChatClient;

    @Autowired
    private RyProductMapper ryProductMapper;
    @Autowired
    private RyServiceMapper ryServiceMapper;
    @Autowired
    private RyConsumptionMapper ryConsumptionMapper;

    @Autowired
    private RyCustomerMapper ryCustomerMapper;
    @Autowired
    private AiModelConfigMapper aiModelConfigMapper;

    @Autowired
    private OpenAiChatModel baseChatModel;

    @Autowired
    private OpenAiApi baseOpenAiApi;

    public AIDialogueImpl(ChatClient.Builder chatClient) {
        this.aIChatClient = chatClient
                .build();
    }

    /**
     * 推送模块-AI提示词分析
     * @return
     */
    @Override
    public Flux<String> AIchat(AIDto aiDto) {
        Long customerId = aiDto.getCustomerId();
        String query = aiDto.getContent();

        // 查询数据库
        AiModelConfig aiModelConfig = new AiModelConfig();
        aiModelConfig.setModelName(aiDto.getModelName());
        List<AiModelConfig> aiModelConfigs = aiModelConfigMapper.selectAiModelConfigList(aiModelConfig);

        if (aiModelConfigs.isEmpty()) {
            throw new RuntimeException("模型为空");
        }
        AiModelConfig aiModelConfig1 = aiModelConfigs.get(0);
        System.out.println(aiModelConfig1.getApiKey());

        RyProduct ryProduct = new RyProduct();
        ryProduct.setStatus(1L);// 上架状态
        RyService ryService = new RyService();
        RyConsumption ryConsumption = new RyConsumption();
        if (customerId != null) { // 逻辑 ①有customerId，就根据customerId查询 ②没有customerId，就查询所有的数据进行分析
            ryConsumption.setCustomerId(customerId);
        }

        ryConsumption.setDelFlag(0L);// 未删除

        List<RyProduct> ryProducts = ryProductMapper.selectAIRyProductList(ryProduct);
        List<RyService> ryServices = ryServiceMapper.selectRyServiceAIByServiceList(ryService);
        List<RyConsumption> ryConsumptions = ryConsumptionMapper.selectAIRyConsumptionList(ryConsumption);

        String ryProductsString = JSON.toJSONString(ryProducts);
        String ryServicesString = JSON.toJSONString(ryServices);
        String ryConsumptionsString = JSON.toJSONString(ryConsumptions);

        System.out.println(ryConsumptionsString);

        // 处理可能的 null 值
        ryProductsString = ryProductsString == null ? "该用户无消费记录" : ryProductsString;
        ryServicesString = ryServicesString == null ? "暂时无产品上架" : ryServicesString;
        ryConsumptionsString = ryConsumptionsString == null ? "暂无服务项目" : ryConsumptionsString;

        System.out.println();
        System.out.println("转数据库数据为json：" + !ryProductsString.isEmpty() +
                !ryServicesString.isEmpty() + !ryConsumptionsString.isEmpty());

        //设置大模型参数
        OpenAiApi groqApi = baseOpenAiApi.mutate()
                .baseUrl(aiModelConfig1.getBaseUrl())
                .apiKey(aiModelConfig1.getApiKey())
                .build();
        OpenAiChatModel gpt4Model = baseChatModel.mutate()
                .openAiApi(groqApi)
                .defaultOptions(OpenAiChatOptions.builder().model(aiModelConfig1.getModel()).temperature(0.7).build())
                .build();
        return ChatClient.builder(gpt4Model).build()
                .prompt()
                .system("你是美容院的小助手，请结合消费记录、产品列表、服务列表数据，根据客户过往消费习惯和需求，" +
                        "有针对性地为客户推荐合适的产品或服务，并说明推荐理由，回答要亲切友好，只能回答一次，不要反问，不要谎造数据")
                .system("requirement: 请结合以下数据,分析该客户，并生成推销话术;" +
                        "本店美容院服务列表如下：" + ryServicesString +
                        "本店现有的产品列表如下：" + ryProductsString +
                        "该客户的历史消费记录如下：" + ryConsumptionsString)
                .user("注意店内数据和客户消费记录数据分开，不能搞混，只能回答一次，不要反问，不要无中生有，结合数据回答问题，：" + query)
                .stream().content();
    }

    /**
     * 分析用户画像 给技师微信推送的AI话术（限制字数）
     * 
     * @return
     */
    public String AnalyzeUsersChat(Long customerId) {

        System.out.println("分析用户画像" + customerId);
        RyProduct ryProduct = new RyProduct();
        ryProduct.setStatus(1L);// 上架状态
        RyService ryService = new RyService();
        RyConsumption ryConsumption = new RyConsumption();
        if (customerId != null) { // 逻辑 ①有customerId，就根据customerId查询 ②没有customerId，就查询所有的数据进行分析
            ryConsumption.setCustomerId(customerId);
        }

        ryConsumption.setDelFlag(0L);// 未删除

        List<RyProduct> ryProducts = ryProductMapper.selectAIRyProductList(ryProduct);
        List<RyService> ryServices = ryServiceMapper.selectRyServiceAIByServiceList(ryService);
        List<RyConsumption> ryConsumptions = ryConsumptionMapper.selectAIRyConsumptionList(ryConsumption);

        String ryProductsString = JSON.toJSONString(ryProducts);
        String ryServicesString = JSON.toJSONString(ryServices);
        String ryConsumptionsString = JSON.toJSONString(ryConsumptions);
        System.out.println(ryConsumptionsString);

        // 处理可能的 null 值
        ryProductsString = ryProductsString == null ? "该用户无消费记录" : ryProductsString;
        ryServicesString = ryServicesString == null ? "暂时无产品上架" : ryServicesString;
        ryConsumptionsString = ryConsumptionsString == null ? "暂无服务项目" : ryConsumptionsString;

        System.out.println();
        System.out.println("转数据库数据为json：" + !ryProductsString.isEmpty() +
                !ryServicesString.isEmpty() + !ryConsumptionsString.isEmpty());

        OpenAiApi groqApi = baseOpenAiApi.mutate()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode")
                .apiKey("sk-5deca8bee4f94128b2b826fef5f84c6e")
                .build();
        OpenAiChatModel gpt4Model = baseChatModel.mutate()
                .openAiApi(groqApi)
                .defaultOptions(OpenAiChatOptions.builder().model("deepseek-v3").temperature(0.7).build())
                .build();


        return ChatClient.builder(gpt4Model).build()
                .prompt()
                .system("你是美容院的小助手，请结合消费记录、产品列表、服务列表数据，根据客户过往消费习惯和需求，" +
                        "有针对性地为客户推荐合适的产品或服务，并说明推荐理由，回答要亲切友好，只能回答一次，不要反问，不要谎造数据")
                .system("requirement: 请结合以下数据,分析该客户，并生成推销话术;" +
                        "本店美容院服务列表如下：" + ryServicesString +
                        "本店现有的产品列表如下：" + ryProductsString +
                        "该客户的历史消费记录如下：" + ryConsumptionsString)
                .user("注意店内数据和客户消费记录数据分开，不能搞混，只能回答一次，不要反问，不要无中生有，结合数据回答问题(限制在两百字符以内)")
                .call()
                .content();
    }

    /**
     * 分析多个用户 画像
     *
     * @return
     */
    public Flux<String> AnalyzeListUsers(AIDto aiDto) {

        // 查询数据库
        AiModelConfig aiModelConfig = new AiModelConfig();
        aiModelConfig.setModelName(aiDto.getModelName());
        List<AiModelConfig> aiModelConfigs = aiModelConfigMapper.selectAiModelConfigList(aiModelConfig);

        if (aiModelConfigs.isEmpty()) {
            throw new RuntimeException("为空");
        }
        AiModelConfig aiModelConfig1 = aiModelConfigs.get(0);
        System.out.println(aiModelConfig1.getApiKey());


        List<Long> customerIds = aiDto.getCustomerIds();
        System.out.println("分析用户画像,勾选的客户数量：" + customerIds.size());

        RyProduct ryProduct = new RyProduct();
        ryProduct.setStatus(1L);// 上架状态
        RyService ryService = new RyService();

        // 存储每个客户的消费记录
        Map<Long, String> customerConsumptionMap = new HashMap<>();
        for (Long customerId : customerIds) {
            RyConsumption ryConsumption = new RyConsumption();
            ryConsumption.setCustomerId(customerId);
            ryConsumption.setDelFlag(0L);// 未删除

            List<RyConsumption> ryConsumptions = ryConsumptionMapper.selectAIRyConsumptionList(ryConsumption);
            String ryConsumptionsString = JSON.toJSONString(ryConsumptions);
            ryConsumptionsString = ryConsumptionsString == null ? "暂无服务项目" : ryConsumptionsString;
            customerConsumptionMap.put(customerId, ryConsumptionsString);
        }

        // 拼接每个客户的消费记录
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Long, String> entry : customerConsumptionMap.entrySet()) {

            // 查询客户姓名
            String customerName;
            RyCustomer customer = ryCustomerMapper.selectRyCustomerById(entry.getKey());
            if (customer != null && customer.getName() != null) {
                customerName = customer.getName();
            } else {
                customerName = "未知姓名";
            }

            sb.append("客户ID: ").append(entry.getKey())
                    .append("，姓名: ").append(customerName)
                    .append(" 的历史消费记录如下：").append(entry.getValue()).append("\n");
        }

        List<RyProduct> ryProducts = ryProductMapper.selectAIRyProductList(ryProduct);
        List<RyService> ryServices = ryServiceMapper.selectRyServiceAIByServiceList(ryService);

        String ryProductsString = JSON.toJSONString(ryProducts);
        String ryServicesString = JSON.toJSONString(ryServices);

        System.out.println(sb);

        // 处理可能的 null 值
        ryProductsString = ryProductsString == null ? "该用户无消费记录" : ryProductsString;
        ryServicesString = ryServicesString == null ? "暂时无产品上架" : ryServicesString;

        System.out.println();
        System.out.println("转数据库数据为json：" + !ryProductsString.isEmpty() +
                !ryServicesString.isEmpty() + !sb.isEmpty());

        //设置大模型参数
        OpenAiApi groqApi = baseOpenAiApi.mutate()
                .baseUrl(aiModelConfig1.getBaseUrl())
                .apiKey(aiModelConfig1.getApiKey())
                .build();
        OpenAiChatModel gpt4Model = baseChatModel.mutate()
                .openAiApi(groqApi)
                .defaultOptions(OpenAiChatOptions.builder().model(aiModelConfig1.getModel()).temperature(0.7).build())
                .build();

        return ChatClient.builder(gpt4Model).build()
                .prompt()
                .system("你是美容院的小助手，请结合我给你的美容院先有的产品列表、服务项目列表数据基础上，分析多名客户的消费记录来分析说明（一个客户对应一个customerId）。")
                .system("requirement: 请结合以下数据,分析多名客户的消费记录" +
                        "本店美容院服务项目列表如下：" + ryServicesString +
                        "本店现有的产品列表如下：" + ryProductsString +
                        "每个客户的历史消费记录如下：" + sb)
                .user("注意店内数据和客户消费记录数据分开，不能搞混，只能回答一次，不要反问，不要无中生有，结合数据回答问题")
                .stream()
                .content();

    }

}
